<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/

class attachment_api{

	public function insertUnused($data){
		$attachmentdb = load_db('attachment');
		$data['table_id'] = '111';
		if($aid = $attachmentdb->addToAttachIndexTable($data)){
			$data['aid'] = $aid;
			return $attachmentdb->addToUnusedTable($data);
		}
		return false;
	}

	public function insertReal($data,$itemid){
		$attachmentdb = load_db('attachment');
		$data['item_id'] = $itemid;
		if($aid = $attachmentdb->addToAttachIndexTable($data)){
			$data['aid'] = $aid;
			return $this->addAttachByItem($itemid,$data);
		}
		return false;
	}

	private function addAttachByItem($itemid,$data){
		$attachmentdb = load_db('attachment');
		$result = $attachmentdb->addAttachByItem($itemid,$data);
		return $result;
	}
	
	public function getUnused($aid){
		$attachmentdb = load_db('attachment');
		if($data = $attachmentdb->getUnused($aid)){
			return $data;
		}
		return false;
	}

	public function updateDownloads($aid){
		$attachmentdb = load_db('attachment');
		$attachmentdb->updateDownloads($aid);
	}
	

	public function updateDBAttach($aid,$itemid,$data){
		return load_db('attachment')->updateReal($aid,$itemid,$data);
	}

	public function findSubImageCoverByItem($itemid,$aid){
		$attachmentdb = load_db('attachment');
		return $attachmentdb->findSubImageCoverByItem($itemid,$aid);
	}

	public function moveToReal($aid,$itemid,$desc,$iscover=false){
		$attachmentdb = load_db('attachment');
		if($data = $attachmentdb->getReal($aid,$itemid)){
			return $data;
		}
		if($data = $attachmentdb->getUnused($aid)){
			$data['description'] = $desc;
			if($this->addAttachByItem($itemid,$data)){
				if($data['isimage']){
					$this->createThumb($data, $iscover);
				}
				if($attachmentdb->updateIndex($aid,$itemid)){
					$attachmentdb->deleteUnused($aid);
					return $data;
				}
			}
		}
		return false;
	}

	public function saveRemoteImage($image,$url,$itemid,$desc,$iscover=false){
		$pz = &get_instance();
		$userid = $pz->cuser['uid'];
		$content = get_contents($image,2,true);
		//$file_extension = strtolower(fileext($image));
		$file_extension = getExtFromContentType($content['content_type']);
		if($file_extension){
			$file_name = $userid.'_'.random(20).'';
			$date_dir = 'data/attachments/'.date("Y/m/d/");
			$save_path = BASEPATH . $date_dir;
			$file_path = $save_path.$file_name.'.'.$file_extension;
			(!is_dir($save_path))&&@mkdir($save_path,0777,true);
			if(!empty($content) && @file_put_contents($file_path,$content) > 0){
				$this->createThumb(array('attachment'=>$date_dir.$file_name,'fileext'=>$file_extension), $iscover);
				$data['isimage']=in_array($file_extension, array('jpg','jpeg','png','gif'))?1:0;
				if($data['isimage']){
					$img_pro = @getimagesize($file_path);
					$data['width']=$img_pro['0'];
					$data['height']=$img_pro['1'];
				}
				$data['filename']=$file_name.'.'.$file_extension;
				$data['filesize']=@filesize($file_path);
				$data['attachment']=$date_dir.$file_name;
				$data['user_id']=$userid;
				$data['fileext']=$file_extension;
				$data['remote']=$image;
				$data['source']=$url;
				$data['description']=$desc;
				$data['thumb']=0;
				if($aid = $this->insertReal($data, $itemid)){
					$data['aid'] = $aid;
					return $data;
				}
			}
		}

		return false;
	}

	public function saveRemoteVideo($image,$flv,$url,$itemid,$desc,$iscover=false){
		$pz = &get_instance();
		$userid = $pz->cuser['uid'];
		$content = get_contents($image);
		$file_extension = strtolower(fileext($image));
		if(!in_array($file_extension, array('png','jpg','jpeg','gif','bmp'))){
			$file_extension = 'jpg';
		}
		$file_name = $userid.'_'.random(20).'';
		$date_dir = 'data/attachments/'.date("Y/m/d/");
		$save_path = BASEPATH . $date_dir;
		$file_path = $save_path.$file_name.'.'.$file_extension;
		(!is_dir($save_path))&&@mkdir($save_path,0777,true);
		if(!empty($content) && @file_put_contents($file_path,$content) > 0){
			$this->createThumb(array('attachment'=>$date_dir.$file_name,'fileext'=>$file_extension), $iscover);
			$data['isimage']=2; //2 means video
			$img_pro = @getimagesize($file_path);
			$data['width']=$img_pro['0'];
			$data['height']=$img_pro['1'];
			$data['filename']=$file_name.'.'.$file_extension;
			$data['filesize']=@filesize($file_path);
			$data['attachment']=$date_dir.$file_name;
			$data['user_id']=$userid;
			$data['fileext']=$file_extension;
			$data['remote']=$flv;
			$data['source']=$url;
			$data['description']=$desc;
			$data['thumb']=0;
			if($aid = $this->insertReal($data, $itemid)){
				$data['aid'] = $aid;
				return $data;
			}
		}

		return false;
	}

	public function createThumb($attach,$iscover){
		$covertypes = array('_large','_middle','_square');
		$setting = load_api('setting')->getUploadSetting();
		$dest_file_path = BASEPATH.$attach['attachment'].'.'.$attach['fileext'];
		$imagelib = &load_class('ImageLib');
		$largewidth = $setting['largewidth']?$setting['largewidth']:600;
		$squarewidth = $setting['squarewidth']?$setting['squarewidth']:200;
		//$deletesource = $setting['delete_source']?$setting['delete_source']:0;
		$imagelib->create_thumb($dest_file_path, 'large', $largewidth);
		$imagelib->crop_square($dest_file_path, $squarewidth);
		if($iscover){
			$wftwidth = $setting['wftwidth']?$setting['wftwidth']:220;
			$imagelib->create_thumb($dest_file_path, 'middle', $wftwidth);
		}
	}

	public function deleteUnusedByUser($uid){
		$attachmentdb = load_db('attachment');
		$unuseds = $attachmentdb->findUnusedByUser($uid);
		foreach ($unuseds as $unused){
			$attachmentdb->deleteUnused($unused['aid']);
			$this->deleteAttachFiles($unused);
		}
	}

	public function delAttachByItem($itemid){
		$attachmentdb = load_db('attachment');
		$atts = $attachmentdb->findAttachByItem($itemid);
		foreach ($atts as $attach){
			$attachmentdb->deleteReal($attach['aid'],$itemid);
			$this->deleteAttachFiles($attach);
			load_api('event')->deleteAttach($attach);
		}
	}
	public function delAttachByAidAndItem($aid,$itemid){
		$attachmentdb = load_db('attachment');
		$attach = $attachmentdb->getAttachById($aid);
		if($attach){
			$attachmentdb->deleteReal($attach['aid'],$itemid);
			$this->deleteAttachFiles($attach);
			load_api('event')->deleteAttach($attach);
		}
	}
	public function getAttachById($aid){
		return load_db('attachment')->getAttachById($aid);
	}
	
	public function findDBAttachByItem($itemid){
		return load_db('attachment')->findAttachByItem($itemid);
	}

	public function findAttachByItem($itemid){
		$attaches = $this->findDBAttachByItem($itemid);
		$item = load_db('share/item')->findBy('item_id',$itemid);
		if($attaches){
			foreach ($attaches as $key=>$att){
				if(strpos($item['image_path_0'], $att['attachment'])!==false){
					$attaches[$key]['iscover'] = true;
				}
			}
		}

		return $attaches;
	}

	public function deleteAttachFiles($attach){
		if($attach['isimage']){
			file_exists(BASEPATH.$attach['attachment'].'_large.'.$attach['fileext']) && unlink(BASEPATH.$attach['attachment'].'_large.'.$attach['fileext']);
			file_exists(BASEPATH.$attach['attachment'].'_middle.'.$attach['fileext']) && unlink(BASEPATH.$attach['attachment'].'_middle.'.$attach['fileext']);
			file_exists(BASEPATH.$attach['attachment'].'_small.'.$attach['fileext']) && unlink(BASEPATH.$attach['attachment'].'_small.'.$attach['fileext']);
			file_exists(BASEPATH.$attach['attachment'].'_square_like.'.$attach['fileext']) && unlink(BASEPATH.$attach['attachment'].'_square_like.'.$attach['fileext']);
			file_exists(BASEPATH.$attach['attachment'].'_square.'.$attach['fileext']) && unlink(BASEPATH.$attach['attachment'].'_square.'.$attach['fileext']);
			file_exists(BASEPATH.$attach['attachment'].'_home.'.$attach['fileext']) && unlink(BASEPATH.$attach['attachment'].'_home.'.$attach['fileext']);
		}
		file_exists(BASEPATH.$attach['attachment'].'.'.$attach['fileext']) && unlink(BASEPATH.$attach['attachment'].'.'.$attach['fileext']);
	}


	public function simpleUpload($uploadDirectory,$replaceOldFile = FALSE,$allowedExtensions = array(),$sizeLimit = 10485760,$fname=false){
		$allowedExtensions = array_map("strtolower", $allowedExtensions);
		if (isset($_GET['qqfile'])) {
			$file = new qqUploadedFileXhr();
		} elseif (isset($_FILES['qqfile'])) {
			$file = new qqUploadedFileForm();
		} else {
			$file = false;
		}

		if (!is_writable($uploadDirectory)){
			return array('success' => false, 'message' => lang('upload_dir_permission','tip'));
		}

		if (!$file){
			return array('success' => false, 'message' => lang('upload_nofile','tip'));
		}

		$size = $file->getSize();

		if ($size == 0) {
			return array('success' => false, 'message' => lang('upload_nofile','tip'));
		}

		if ($size > $sizeLimit) {
			return array('success' => false, 'message' => lang('upload_exceed_max_size','tip'));
		}

		$pathinfo = pathinfo($file->getName());
		//$filename = $pathinfo['filename'];
		$filename = ($fname)?$fname:md5(uniqid());
		//$filename = time().'';
		$ext = $pathinfo['extension'];

		if($allowedExtensions && !in_array(strtolower($ext), $allowedExtensions)){
			$these = implode(', ', $allowedExtensions);
			return array('success' => false, 'message' => lang('upload_invalid_ext','tip'));
		}

		if(!$replaceOldFile){
			/// don't overwrite previous files that were uploaded
			while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
				$filename .= rand(10, 99);
			}
		}

		if ($file->save($uploadDirectory . $filename . '.' . $ext)){
			return array('success'=>true,'data'=>array('filename'=>$filename,'ext'=>$ext));
		} else {
			return array('success' => false, 'message' => lang('upload_can_not_save','tip'));
		}
	}
}

class qqUploadedFileXhr {
	/**
	 * Save the file to the specified path
	 * @return boolean TRUE on success
	 */
	function save($path) {
		$input = fopen("php://input", "r");
		$temp = tmpfile();
		$realSize = stream_copy_to_stream($input, $temp);
		fclose($input);

		if ($realSize != $this->getSize()){
			return false;
		}

		$target = fopen($path, "w");
		fseek($temp, 0, SEEK_SET);
		stream_copy_to_stream($temp, $target);
		fclose($target);

		return true;
	}
	function getName() {
		return $_GET['qqfile'];
	}
	function getSize() {
		if (isset($_SERVER["CONTENT_LENGTH"])){
			return (int)$_SERVER["CONTENT_LENGTH"];
		} else {
			throw new Exception('Getting content length is not supported.');
		}
	}
}

/**
 * Handle file uploads via regular form post (uses the $_FILES array)
 */
class qqUploadedFileForm {
	/**
	 * Save the file to the specified path
	 * @return boolean TRUE on success
	 */
	function save($path) {
		if(!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)){
			return false;
		}
		return true;
	}
	function getName() {
		return $_FILES['qqfile']['name'];
	}
	function getSize() {
		return $_FILES['qqfile']['size'];
	}
}
